#!/bin/sh

# manage local, gitolite-controlled, copies of read-only upstream repos.

repo=$2

url=$(gitolite git-config $repo gitolite-options.upstream.url)
[ -z "$url" ] && exit 0     # exit if no url was specified

cd $GL_REPO_BASE/$repo.git || exit 1

[ "$1" != "fetch" ] && {
    nice=$(gitolite git-config $repo gitolite-options.upstream.nice)
    [ -n "$nice" ] && find FETCH_HEAD -mmin -$nice 2>/dev/null | grep . >/dev/null && exit 0
}

git fetch -q "$url" '+refs/*:refs/*'

# ----------------------------------------------------------------------

# FEATURES:
# * invokes upstream fetch on each local fetch
#   (unless the optional 'nice' setting is enabled)
# * can force a fetch (ignoring 'nice' value) from server CLI

# INSTRUCTIONS:
#
# * uncomment 'upstream' in the ENABLE list in the rc file.
# * add option lines to conf file.  For example:
#
#       repo git
#           R                       =   @all
#           RW+ my-company/         =   @developers
#
#           option  upstream.url    =   https://git.kernel.org/pub/scm/git/git.git
#           option  upstream.nice   =   120
#
# * to force a fetch on the server shell (or via cron), run this command:
#       gitolite ../triggers/upstream fetch reponame

# ADDITIONAL NOTES:
# * restrict local pushes to a namespace that the upstream won't use
#   (otherwise the next fetch will wipe them out)
# * if the upstream URL changes, just change the conf and push admin repo
# * the 'nice' setting is in minutes and is optional; it is the minimum
#   elapsed time between 2 upstream fetches.

# USAGE EXAMPLE:
#
# Let's say you want to keep a read-only local mirror of all your github repos
# on your local gitolite installation.  Assuming your github usernames are the
# same as your local usernames, and you have updated GIT_CONFIG_KEYS in the rc
# file to allow 'config' lines, you can do this:
#
#   repo github/CREATOR/..*
#       C   = @all
#       R   = @all
#       option upstream.url                         =   https://github.com/%GL_REPO.git
#       option upstream.nice                        =   120
#       config url.https://github.com/.insteadOf    =   https://github.com/github/
#
# Now you can make local, read-only, clones of all your github repos with
#
#   git ls-remote gitolite:github/sitaramc/gitolite
#   git ls-remote gitolite:github/sitaramc/hap
#   (etc)
#
# and if milki were also a user on this gitolite instance, then
#
#   git ls-remote gitolite:github/milki/xclip
#   git ls-remote gitolite:github/milki/ircblogger
#   (etc)
